import 'package:flutter/material.dart';
import 'package:x3_base_package/x3_base_package.dart';
import 'package:x3_business_core/business_customer/page/business_customer_details_service_coupons.dart';
import 'package:x3_business_core/business_customer/page/business_customer_details_service_ht.dart';
import 'package:x3_business_core/business_customer/page/business_customer_details_service_ht_details.dart';
import 'package:x3_business_core/business_customer/page/business_customer_details_service_sms.dart';
import 'package:x3_business_core/business_customer/page/business_customer_details_service_xyk.dart';
import 'package:x3_business_core/business_customer/page/business_customer_details_service_xyk_details.dart';
import 'package:x3_business_core/business_customer/ful_components/business_customer_details_coupons_scheme_item.dart';

class BusinessCustomerDetailsService extends StatefulWidget {
  BusinessCustomerDetailsService({Key key, @required this.vipId}) : super(key: key);

  final String vipId;

  @override
  _BusinessCustomerDetailsServiceState createState() => _BusinessCustomerDetailsServiceState();
}

class _BusinessCustomerDetailsServiceState extends State<BusinessCustomerDetailsService> with AutomaticKeepAliveClientMixin {
  final List<Color> _depotVipDetailsSmsContentItemColor = [
    Color(0xFFF04134),
    Color(0xFFFF8A00),
    Color(0xFF36C65A),
    Color(0xFF5E96F4),
    Color(0xFFCC66CC),
  ];

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BaseScreenRefreshComponent(
      request: BaseScreenRequestModel('/vip/customer/query/servicetools/broadcast/${widget.vipId}', method: BaseHttpMethodEnum.GET, params: {'vipId': widget.vipId}),
      builder: (BaseHttpResultModel result) {
        BaseCatalogResponseModel catalogResponse = BaseCatalogResponseModel(result);
        return _buildMainScaffold(context, catalogResponse);
      },
    );
  }

  Widget _buildMainScaffold(BuildContext context, BaseCatalogResponseModel catalogResponse) {
    return SingleChildScrollView(
      padding: const EdgeInsets.only(bottom: 20.0),
      child: Column(children: _buildResponseWidgets(context, catalogResponse)),
    );
  }

  List<Widget> _buildResponseWidgets(BuildContext context, BaseCatalogResponseModel catalogResponse) {
    List<Widget> widgets = [];
    catalogResponse.response.forEach((response) {
      String fieldName = response.fieldName;
      if (fieldName == 'contentServerTitle') {
        // 日常维护
        widgets.add(_buildDepotVipDetailsMaintain(context, response, catalogResponse.dataSource));
      } else if (fieldName == 'contentCouponTitle') {
        //优惠券
        widgets.add(_buildDepotVipDetailsCouponWidget(context, response, catalogResponse.dataSource));
      } else if (fieldName == 'contentHtTitle') {
        // 话题
        widgets.add(_buildDepotVipDetailsHtWidget(context, response, catalogResponse.dataSource));
      } else if (fieldName == 'contentXykTitle') {
        //心意卡
        widgets.add(_buildDepotVipDetailsXykWidget(context, response, catalogResponse.dataSource));
      } else if (fieldName == 'contentSmsTitle') {
        // 话术
        widgets.add(_buildDepotVipDetailsSmsWidget(context, response, catalogResponse.dataSource));
      }
    });
    return widgets;
  }

  Widget _buildDepotVipDetailsMaintain(BuildContext context, BaseHttpResponseModel response, dynamic dataSource) {
    List<dynamic> items = dataSource[response.fieldName];
    // 删除短信
    int _b2Index = items.indexWhere((element) {
      String buttonId = BaseUtils.getKeyData(element, 'buttonId');
      return buttonId == 'B2';
    });
    if (_b2Index != -1) items.removeAt(_b2Index);
    return _buildServiceCardContainer(
      context: context,
      name: response.name,
      child: Row(
        children: items.map((dynamic item) {
          String buttonName = BaseUtils.getKeyData(item, 'buttonName').toString();
          String buttonImg = BaseUtils.getKeyData(item, 'buttonImg').toString();
          String useValue = BaseUtils.getKeyData(item, 'useValue').toString();
          return Expanded(child: _buildDepotVipDetailsMaintainItem(context, buttonName, buttonImg, useValue));
        }).toList(),
      ),
    );
  }

  /// 打电话 发短信
  Widget _buildDepotVipDetailsMaintainItem(BuildContext context, String buttonName, String buttonImg, String useValue) {
    return GestureDetector(
      onTap: () => _onDepotVipDetailsMaintainItem(context, buttonName, useValue),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            width: 48,
            height: 48,
            alignment: Alignment.center,
            margin: EdgeInsets.only(bottom: 8.0),
            decoration: BoxDecoration(color: Theme.of(context).scaffoldBackgroundColor, borderRadius: BorderRadius.circular(48.0)),
            child: BaseImageComponent(imageUrl: buttonImg, width: 40.0, height: 40.0),
          ),
          Text(buttonName)
        ],
      ),
    );
  }

  void _onDepotVipDetailsMaintainItem(BuildContext context, String buttonName, String useValue) {
    switch (buttonName) {
      case '打电话':
        this._sendMaintain('/vip/customer/server/tool/calltel', {'vipId': widget.vipId}, () => BaseUrlLauncherUtil.tel(useValue));
        break;
      case '发短信':
        BaseRouterUtil.getInstance().pushNamed(BusinessCustomerDetailsServiceSms.sName, arguments: {'title': '选择短信内容模版', 'inputApi': '', 'vipId': widget.vipId, 'phoneNumber': useValue, 'sms': true, 'privateWx': false});
        break;
      case '发微信':
        BaseRouterUtil.getInstance().pushNamed(BusinessCustomerDetailsServiceSms.sName, arguments: {'title': '选择微信内容模版', 'inputApi': '', 'vipId': widget.vipId, 'sms': false, 'privateWx': true});
        break;
      case '发企微':
        BaseRouterUtil.getInstance().pushNamed(BusinessCustomerDetailsServiceSms.sName, arguments: {'title': '选择企业微信内容模版', 'inputApi': '', 'vipId': widget.vipId, 'sms': false, 'privateWx': false, 'enterpriseWx': true});
        break;
    }
  }

  /// 打电话  发短信  发微信  发企微
  void _sendMaintain(String service, Map<String, dynamic> params, Function callback) {
    BaseComponentUtils.showLoadingDialog(context);
    dioUtil.fetch(service, params: params).then((BaseHttpResultModel result) {
      BaseComponentUtils.hideLoadingDialog(context);
      if (result.success == true) {
        callback();
      }
    });
  }

  ///弹出评论框
  void showLeaveAMessageWidget(BuildContext context) {
    String leavemessage = '';
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Container(
            color: Colors.white,
            padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom, right: 12, left: 12, top: 12),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: BaseTextField(
                        hintText: '请输入你的留言吧',
                        autoFocus: true,
                        maxLines: 10,
                        onChanged: (String comment) {
                          leavemessage = comment;
                        },
                        onSubmitted: (String comment) {
                          leavemessage = comment;
                          this._sendMaintain('/vip/customer/server/tool/leavemessage', {'vipId': widget.vipId, 'leaveMessage': leavemessage}, () {
                            BaseUtils.showToast('留言成功');
                            Navigator.of(context).pop();
                          });
                        },
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        this._sendMaintain('/vip/customer/server/tool/leavemessage', {'vipId': widget.vipId, 'leaveMessage': leavemessage}, () {
                          BaseUtils.showToast('留言成功');
                          Navigator.of(context).pop();
                        });
                      },
                      child: Icon(Icons.publish_outlined, color: Colors.black),
                    )
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildDepotVipDetailsCouponWidget(BuildContext context, BaseHttpResponseModel response, dynamic dataSource) {
    return _buildServiceCardContainer(
      context: context,
      name: response.name,
      child: _buildDepotVipDetailsCouponContent(context, response, dataSource),
      onPress: () => BaseRouterUtil.getInstance().pushNamed(
        BusinessCustomerDetailsServiceCoupons.sName,
        arguments: {'title': response.name, 'inputApi': response.inputApi, 'vipId': widget.vipId},
      ),
    );
  }

  Widget _buildDepotVipDetailsCouponContent(BuildContext context, BaseHttpResponseModel response, dynamic dataSource) {
    return BaseScreenRefreshComponent(
      request: BaseScreenRequestModel(response.inputApi, params: {'vipId': widget.vipId, 'pageIndex': 1, 'pageSize': 3}),
      controller: BaseFutureController(),
      builder: (BaseHttpResultModel result) {
        List<dynamic> items = result.data;
        return items.length == 0
            ? BaseEmptyComponent()
            : ListView.separated(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: items.length,
                itemBuilder: (BuildContext itemContext, int index) {
                  return Container(
                    padding: const EdgeInsets.symmetric(vertical: 8.0),
                    child: _buildDepotVipDetailsCouponContentItem(context, items[index]),
                  );
                },
                separatorBuilder: (BuildContext itemContext, int index) {
                  return Container(
                    padding: const EdgeInsets.symmetric(vertical: 10.0),
                    child: BaseComponentUtils.buildHorizontalDivider(),
                  );
                },
              );
      },
    );
  }

  Widget _buildDepotVipDetailsCouponContentItem(BuildContext context, dynamic item) {
    return BusinessCustomerDetailsCouponsSchemeItem(item: item, couponState: '0');
  }

  Widget _buildDepotVipDetailsHtWidget(BuildContext context, BaseHttpResponseModel response, dynamic dataSource) {
    return _buildServiceCardContainer(
      context: context,
      name: response.name,
      child: _buildDepotVipDetailsHtContent(context, response, dataSource),
      onPress: () => BaseRouterUtil.getInstance().pushNamed(
        BusinessCustomerDetailsServiceHt.sName,
        arguments: {'title': response.name, 'inputApi': response.inputApi, 'vipId': widget.vipId},
      ),
    );
  }

  Widget _buildDepotVipDetailsHtContent(BuildContext context, BaseHttpResponseModel response, dynamic dataSource) {
    return BaseScreenRefreshComponent(
      request: BaseScreenRequestModel(response.inputApi, params: {'vipId': widget.vipId, 'pageIndex': 1, 'pageSize': 3}),
      controller: BaseFutureController(),
      builder: (BaseHttpResultModel result) {
        List<dynamic> items = result.data;
        return items.length == 0
            ? BaseEmptyComponent()
            : ListView.separated(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: items.length > 3 ? 3 : items.length,
                itemBuilder: (BuildContext itemContext, int index) {
                  return Container(
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    child: _buildDepotVipDetailsHtContentItem(context, items[index]),
                  );
                },
                separatorBuilder: (BuildContext itemContext, int index) => BaseComponentUtils.buildHorizontalDivider(),
              );
      },
    );
  }

  /// 话题item
  double _htSize = 112;

  Widget _buildDepotVipDetailsHtContentItem(BuildContext context, dynamic item) {
    String filePath = BaseUtils.getKeyData(item, 'filePath').toString();
    return InkWell(
      onTap: () => _goDepotVipDetailsHtDetails(item),
      child: Row(
        children: [
          BaseImageComponent(imageUrl: filePath, width: _htSize, height: _htSize * (3 / 4), fit: BoxFit.cover, circular: 2),
          SizedBox(width: 12),
          Expanded(child: _buildDepotVipDetailsHtContentItemContent(context, item)),
        ],
      ),
    );
  }

  void _goDepotVipDetailsHtDetails(dynamic item) {
    String topicId = BaseUtils.getKeyData(item, 'topicId').toString();
    BaseRouterUtil.getInstance().pushNamed(BusinessCustomerDetailsServiceHtDetails.sName, arguments: {'topicId': topicId});
  }

  /// 话题item
  Widget _buildDepotVipDetailsHtContentItemContent(BuildContext context, dynamic item) {
    String topicTitle = BaseUtils.getKeyData(item, 'topicTitle').toString();
    String topicTypeName = BaseUtils.getKeyData(item, 'topicTypeName').toString().trim();
    String createDate = BaseUtils.getKeyData(item, 'createDate').toString();
    String browseNums = BaseUtils.getKeyData(item, 'browseNums').toString();
    String initCreateDate = BaseTransformUtil.stringToDate(createDate);
    TextStyle textStyle = Theme.of(context).textTheme.subtitle2;
    return Container(
      padding: const EdgeInsets.only(left: 4.0),
      height: _htSize * (3 / 4),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          RichText(
            softWrap: true,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            text: TextSpan(style: Theme.of(context).textTheme.bodyText2, children: [
              topicTypeName.isNotEmpty
                  ? WidgetSpan(
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 4, vertical: 1),
                        color: Colors.red.shade50,
                        child: Text(topicTypeName.toString().trim(), style: Theme.of(context).textTheme.subtitle2.copyWith(color: Colors.red)),
                      ),
                    )
                  : WidgetSpan(child: SizedBox()),
              WidgetSpan(child: SizedBox(width: 2.0)),
              TextSpan(text: topicTitle, style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14)),
            ]),
          ),
          BaseComponentUtils.buildTextSpanWidget([initCreateDate, '浏览$browseNums次'], styles: {0: textStyle, 1: textStyle}),
        ],
      ),
    );
  }

  Widget _buildDepotVipDetailsXykWidget(BuildContext context, BaseHttpResponseModel response, dynamic dataSource) {
    return _buildServiceCardContainer(
      context: context,
      name: response.name,
      child: _buildDepotVipDetailsXykContent(context, response, dataSource),
      onPress: () => BaseRouterUtil.getInstance().pushNamed(BusinessCustomerDetailsServiceXyk.sName, arguments: {'title': response.name, 'inputApi': response.inputApi, 'vipId': widget.vipId}),
    );
  }

  Widget _buildDepotVipDetailsXykContent(BuildContext context, BaseHttpResponseModel response, dynamic dataSource) {
    return BaseScreenRefreshComponent(
      request: BaseScreenRequestModel(response.inputApi, params: {'vipId': widget.vipId, 'pageIndex': 1, 'pageSize': 3}),
      controller: BaseFutureController(),
      builder: (BaseHttpResultModel result) {
        List<dynamic> items = result.data;
        return GridView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, crossAxisSpacing: 5, mainAxisSpacing: 12),
          itemCount: items.length,
          itemBuilder: (BuildContext context, int index) => _buildDepotVipDetailsXykContentItem(items[index]),
        );
      },
    );
  }

  Widget _buildDepotVipDetailsXykContentItem(dynamic item) {
    String facadeImage = BaseUtils.getKeyData(item, 'facadeImage').toString();
    String wishCardTypeName = BaseUtils.getKeyData(item, 'wishCardTypeName').toString();
    double imageWidth = 80.0;
    return InkWell(
      onTap: () => _goDepotVipDetailsXykDetails(item),
      child: Container(
        alignment: Alignment.center,
        child: Stack(
          children: [
            BaseImageComponent(imageUrl: facadeImage, width: imageWidth),
            Positioned(bottom: 0, width: imageWidth, child: Container(alignment: Alignment.center, height: 24.0, child: Text(wishCardTypeName, style: Theme.of(context).textTheme.bodyText2.copyWith(color: Colors.white)), color: Color(0xFF333333).withAlpha(102))),
          ],
        ),
      ),
    );
  }

  void _goDepotVipDetailsXykDetails(dynamic item) {
    String cardId = BaseUtils.getKeyData(item, 'cardId').toString();
    BaseRouterUtil.getInstance().pushNamed(BusinessCustomerDetailsServiceXykDetails.sName, arguments: {'cardId': cardId});
  }

  Widget _buildDepotVipDetailsSmsWidget(BuildContext context, BaseHttpResponseModel response, dynamic dataSource) {
    String phoneNumber = '';
    List<dynamic> contentServerTitleList = dataSource['contentServerTitle'];
    int _index = contentServerTitleList.indexWhere((element) => element['webUrl'] == 'SMS');
    if (_index != -1) phoneNumber = BaseUtils.getKeyData(contentServerTitleList[_index], 'useValue');
    return _buildServiceCardContainer(
      context: context,
      name: response.name,
      child: _buildDepotVipDetailsSmsContent(context, response, dataSource, phoneNumber),
      onPress: () => BaseRouterUtil.getInstance().pushNamed(BusinessCustomerDetailsServiceSms.sName, arguments: {'title': response.name, 'inputApi': response.inputApi, 'vipId': widget.vipId, 'phoneNumber': phoneNumber}),
    );
  }

  Widget _buildDepotVipDetailsSmsContent(BuildContext context, BaseHttpResponseModel response, dynamic dataSource, String phoneNumber) {
    return BaseScreenRefreshComponent(
      request: BaseScreenRequestModel(response.inputApi, method: BaseHttpMethodEnum.GET),
      controller: BaseFutureController(),
      builder: (BaseHttpResultModel result) {
        List<dynamic> items = result.data;
        return items.length == 0
            ? BaseEmptyComponent()
            : GridView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, crossAxisSpacing: 10.0, mainAxisSpacing: 10.0, childAspectRatio: 3.0),
                itemCount: items.length,
                itemBuilder: (BuildContext context, int index) {
                  Map<String, dynamic> item = items[index];
                  return _buildDepotVipDetailsSmsContentItem(context, item, index, phoneNumber);
                },
              );
      },
    );
  }

  Widget _buildDepotVipDetailsSmsContentItem(BuildContext context, Map<String, dynamic> item, int index, String phoneNumber) {
    String value = BaseUtils.getKeyData(item, 'value').toString();
    return InkWell(
      onTap: () => BaseRouterUtil.getInstance().pushNamed(BusinessCustomerDetailsServiceSms.sName, arguments: {'title': "请选择内容模版", 'inputApi': "", 'vipId': widget.vipId, 'value': value, 'phoneNumber': phoneNumber, 'sms': true, 'privateWx': true, 'enterpriseWx': true}),
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(color: _depotVipDetailsSmsContentItemColor[index % _depotVipDetailsSmsContentItemColor.length].withOpacity(0.1), borderRadius: BorderRadius.circular(30.0)),
        child: Text(value, style: Theme.of(context).textTheme.bodyText2.copyWith(color: _depotVipDetailsSmsContentItemColor[index % _depotVipDetailsSmsContentItemColor.length])),
      ),
    );
  }

  Widget _buildServiceCardContainer({BuildContext context, String name, Widget child, Function onPress}) {
    return BaseCardComponent(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.only(bottom: 12.0),
            child: InkWell(
              onTap: onPress,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 4.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(name, style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14)),
                    onPress != null ? BaseComponentUtils.buildListViewRightIcon(context) : SizedBox(),
                  ],
                ),
              ),
            ),
          ),
          child,
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
